package com.wolfking.converter.transform.extend;


import com.wolfking.converter.transform.AbstractExtendTransform;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;

@Slf4j
public class DateFormatTransform extends AbstractExtendTransform<Object> {


    private final String format;


    public DateFormatTransform(String format) {
        this.format = format;
    }

    public DateFormatTransform() {
        this("");
    }

    @Override
    public Object transform(Object value) {
        if (value instanceof LocalDateTime) {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zonedDateTime = ((LocalDateTime) value).atZone(zoneId);
            Instant instant = zonedDateTime.toInstant();
            value = Date.from(instant);
        }
        if (value instanceof LocalDate) {
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zonedDateTime = LocalDateTime.of((LocalDate) value, LocalTime.MIN).atZone(zoneId);
            Instant instant = zonedDateTime.toInstant();
            value = Date.from(instant);
        }
        if (Date.class.isAssignableFrom(value.getClass())) {
            if ("LONG".equals(format)) {
                return ((Date) value).getTime();
            }
            try {
                return new SimpleDateFormat(format).format((Date) value);
            } catch (Exception e) {
                throw new IllegalStateException(String.format("[%s] format date[%s]换换异常",
                        format, value));
            }
        }
        throw new IllegalStateException(String.format("date[%s]换换异常", value));
    }
}
